package service

import (
	"dashenwo.com/dashenwo/micro_srv/search_srv/configs"
	"dashenwo.com/dashenwo/micro_srv/search_srv/genpb"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/repository"
	"github.com/micro/go-micro/v2/util/log"
	"github.com/olivere/elastic/v7"
)

// 定义用户服务
type SearchService struct {
	repo repository.SearchRepository
}

func (s SearchService) User(req *genpb.SearchRequest) (interface{},error) {
	var (
		OrderBy = "create_time"
		Page = 1
		Size = configs.AppConf.Size
	)
	query := elastic.NewBoolQuery()
	query.Must(
		elastic.NewMultiMatchQuery(req.Keyword,"title"),
	)
	if req.OrderBy==""{
		OrderBy = req.OrderBy
	}
	if req.Page >= 0 {
		Page = int(req.Page)
	}
	if req.Size!=0 {
		Size  = int(req.Size)
	}
	var data *elastic.SearchResult
	data, err := s.repo.Query("db_user",query,OrderBy,Page,Size)
	if err != nil {
		log.Error("查询出错了")
	}
	log.Log(data)
	return data,err
}

func (s SearchService) Article(req *genpb.SearchRequest) (*elastic.SearchResult,error)  {
	var (
		OrderBy = "create_time"
		Page = 1
		Size = configs.AppConf.Size
	)
	query := elastic.NewBoolQuery()
	query.Must(
		elastic.NewMultiMatchQuery(req.Keyword,"title","content"),
	)
	if req.OrderBy!=""{
		OrderBy = req.OrderBy
	}
	if req.Page > 0 {
		Page = int(req.Page)
	}
	if req.Size!=0 {
		Size  = int(req.Size)
	}
	var data *elastic.SearchResult
	data, err := s.repo.Query("db_article",query,OrderBy,Page,Size)
	if err != nil {
		log.Error("查询出错了",err)
	}
	log.Log(data)
	return data,err
}

func NewSearchService(repo repository.SearchRepository) *SearchService {
	return &SearchService{
		repo: repo,
	}
}